package org.aceor.mddal.group;

import org.aceor.mddal.config.datasource.Weight;

import javax.sql.DataSource;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.util.logging.Logger;

/**
 * Created by lxue on 16/3/27.
 */
public class DataSourceWrapper implements DataSource {

    private final String dataSourceKey;  //这个DataSource对应的dbKey
    private final String weightStr;//权重信息字符串
    private final Weight weight;  //权重信息
    private final DataSource wrappedDataSource; //被封装的目标DataSource

    public DataSourceWrapper(String dataSourceKey, String weightStr, DataSource wrappedDataSource, int dataSourceIndex) {
        this.dataSourceKey = dataSourceKey;
        this.weightStr = weightStr;
        this.weight = new Weight(weightStr);
        this.wrappedDataSource = wrappedDataSource;
    }

    @Override
    public Connection getConnection() throws SQLException {
        return wrappedDataSource.getConnection();
    }

    @Override
    public Connection getConnection(String username, String password) throws SQLException {
        return wrappedDataSource.getConnection(username, password);
    }

    @Override
    public PrintWriter getLogWriter() throws SQLException {
        return wrappedDataSource.getLogWriter();
    }

    @Override
    public void setLogWriter(PrintWriter out) throws SQLException {
        wrappedDataSource.setLogWriter(out);
    }

    @Override
    public void setLoginTimeout(int seconds) throws SQLException {
        wrappedDataSource.setLoginTimeout(seconds);
    }

    @Override
    public int getLoginTimeout() throws SQLException {
        return wrappedDataSource.getLoginTimeout();
    }

    @Override
    public Logger getParentLogger() throws SQLFeatureNotSupportedException {
        return wrappedDataSource.getParentLogger();
    }

    public boolean isWrapperFor(Class<?> iface) throws SQLException {
        return this.getClass().isAssignableFrom(iface);
    }

    @SuppressWarnings("unchecked")
    public <T> T unwrap(Class<T> iface) throws SQLException {
        try {
            return (T) this;
        } catch (Exception e) {
            throw new SQLException(e);
        }
    }

    public String getDataSourceKey() {
        return dataSourceKey;
    }

    public String getWeightStr() {
        return weightStr;
    }

    public Weight getWeight() {
        return weight;
    }

    public DataSource getWrappedDataSource() {
        return wrappedDataSource;
    }

    public boolean hasReadWeight() {
        return weight.r > 0;
    }

    public boolean hasWriteWeight() {
        return weight.w > 0;
    }
}
